package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

public class CycleDetectionImprove {

    private Graph G;
    private boolean[] visited;
    private boolean hasCycle = false;

    public CycleDetectionImprove(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];
        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                if (dfs(i, i)) {
                    hasCycle = true;
                    break;
                }
            }
        }
    }

    private boolean dfs(int v, int p) {
        visited[v] = true;
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            } else if (w != p) {
                return true;
            }
        }
        return false;
    }

    public boolean hasCycle() {
        return hasCycle;
    }

    public static void main(String[] args) {
        String filename = CycleDetectionImprove.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CycleDetectionImprove cycleDetection = new CycleDetectionImprove(g);
        System.out.println(cycleDetection.hasCycle());

        String filename2 = CycleDetectionImprove.class.getClassLoader().getResource("g2.txt").getPath();
        Graph g2 = new Graph(filename2);
        CycleDetectionImprove cycleDetection2 = new CycleDetectionImprove(g2);
        System.out.println(cycleDetection2.hasCycle());
    }

    /**
     * 对于g.txt的图，当dfs中的 v=2 的时候，此时 2 是从 3 过来的，所以 p=3，
     * 然后遍历2的所有相邻节点，此时会找到 0 3 6 三个节点，这个时候发现 0 这个节点已经被访问过，
     * 并且 0 这个节点跟 2 的父亲节点不是同一个节点，就表示有环
     */
}
